package com.alpha.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.alpha.bom.Professor;
import com.alpha.bom.Student;
import com.alpha.dao.StudentDao;

/**
 * Servlet implementation class AddStudentServlet
 */
@WebServlet("/AddStudentServlet")
@ServletSecurity(@HttpConstraint(rolesAllowed = {"admin"}))
public class AddStudentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static Logger logger = Logger.getLogger(AddStudentServlet.class.getName());
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddStudentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		logger.info(this.getClass().getSimpleName()+" post method started.");
		
		String firstName = "", lastName = "", password = "";
		Professor professor = null;
		
		HttpSession session = request.getSession();
		if(session.getAttribute("user") != null && session.getAttribute("user") instanceof Professor) {
			professor = (Professor) session.getAttribute("user");
		} else {
			response.sendRedirect("Login.jsp");
			return;
		}
		
		if(request.getParameter("first_name") != null && request.getParameter("last_name") != null
				&& request.getParameter("password") != null) {
			firstName = request.getParameter("first_name");
			lastName = request.getParameter("last_name");
			password = request.getParameter("password");
		} else {
			response.sendRedirect("StudentsAdminServlet?error=Invalid+action.");
			return;
		}
		
		Student student = new Student(0, firstName, lastName, true);
		student.setPassword(password);
		
		StudentDao sDao = new StudentDao();
		try {
			sDao.insertStudent(student, professor.getUserId());
			response.sendRedirect("StudentsAdminServlet?success=Successfully+added+student!");
			return;
		} catch (Exception e) {
			logger.error(e.getMessage());
			response.sendRedirect("StudentsAdminServlet?error=Cannot+add+student.");
			return;
		}
	}

}
